package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.pest.AddReportPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.AudioDialog;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 信访举报
 */
public class ReportActivity extends BaseActivity implements UploadFileView, IVoidView {

    @BindView(R.id.et_Content)
    CountEditText et_Content;
    @BindView(R.id.tv_Count)
    TextView tv_Count;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    private AudioDialog audioDialog;

    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    private String content;
    /**
     * 0:文字 1：图片 2：音频 3：视频
     */
    private int FILE_TYPE;
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_report);
        ButterKnife.bind(this);
        setTitleName(R.string.letter_report);
        setTitleRight(R.string.confirm);
        FILE_TYPE=getIntent().getIntExtra("TYPE",0);
        initView();
    }

    private void initView() {
        if (FILE_TYPE!=0) {
            rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
            adapter = new MultiImageAdapter(this, mAddPicClickListener);
            adapter.setList(selectList);
            rvImageRV.setAdapter(adapter);
            adapter.startAudio(new MultiImageAdapter.OnStartPlayAudioClickListener() {
                @Override
                public void startPlayAudio(String path) {
                    if (audioDialog!=null){
                        audioDialog.startPlay(path);
                    }
                }
            });
        }else {
            rvImageRV.setVisibility(View.GONE);
            findViewById(R.id.ll).setVisibility(View.GONE);
        }
        et_Content.setMaxNum(500);
        et_Content.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tv_Count.setText(currentCount+"/500");
            }
        });
    }

    @OnClick({R.id.tv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right://提交
                BaseUtil.hintKb(this);
                content = et_Content.getText().toString().trim();
                if (BaseUtil.isEmpty(content)){
                    ToastUtils.showToast(ReportActivity.this,"请输入举报内容");
                    return;
                }
                if (FILE_TYPE == 0) {
                    addReportData(null);
                }else {
                    if (selectList.size() == 0){
                        ToastUtils.showToast(ReportActivity.this,"请上传附件");
                        return;
                    }
                    List<File> fileList = new ArrayList<>();
                    for (PhotoBean photoBean : selectList){
                        fileList.add(new File(photoBean.getPath()));
                    }
                    LoadDialog.show(this,"正在上传文件...");
                    new UploadFilePest(this).uploadFile(this,fileList);
                }
                break;
        }
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                switch (FILE_TYPE) {
                    case 1://图片
                        PictureSelector.create(ReportActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.MULTIPLE)
                                .maxSelectNum(max)// 最大图片选择数量 int
                                //.previewImage(true)// 是否可预览图片
                                .enableCrop(true).withAspectRatio(4, 3)
                                .compress(true).compressGrade(Luban.CUSTOM_GEAR)
                                .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case 2://音频
                        if (audioDialog==null){
                            audioDialog=new AudioDialog(ReportActivity.this);
                            audioDialog.setCancelable(false);
                            audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                                @Override
                                public void getData(String filePath, int countdown) {
                                    PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                                    selectList.add(photoBean);
                                    if (adapter != null) adapter.notifyDataSetChanged();
                                }
                            });
                        }
                        audioDialog.show(audioDialog.AUDIO_RECODERD);
                        break;
                    case 3://视频
                        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                                .smallVideoWidth(640).smallVideoHeight(480)
                                .recordTimeMax(10 * 1000).maxFrameRate(20)
                                .minFrameRate(8).captureThumbnailsTime(1)
                                .videoBitrate(580000).build();
                        MediaRecorderActivity.goSmallVideoRecorder(ReportActivity.this, ReportActivity.class.getName(), config);
                        break;
                }

            } else {
                ToastUtils.showToast(ReportActivity.this, "最多上传3张");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case MediaRecorderActivity.FOR_RESULT://拍视频
                    String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if (!TextUtils.isEmpty(videoUri)) {
                        String type = videoUri.substring(videoUri.lastIndexOf("."));
                        selectList.add(new PhotoBean(videoUri, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }


    @Override
    public void showError(String message) {
        LoadDialog.dismiss(ReportActivity.this);
        ToastUtils.showToast(ReportActivity.this,message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        List<String> fileIds = new ArrayList<>();
        for (PhotoBean b : beans){
            fileIds.add(b.getId());
        }
        addReportData(fileIds);
    }

    private void addReportData(List<String> fileIds) {
        LoadDialog.show(ReportActivity.this, "提交中...");
        new AddReportPest(this).addReport(content,fileIds);
    }

    @Override
    public void voidView(String string) {
        LoadDialog.dismiss(ReportActivity.this);
        ToastUtils.showToast(ReportActivity.this,string);
        finish();
    }
}
